package com.atguigu.gulimall.product.exeception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname GulimallExceptionCotrollerAdvice
 * @Description TODO
 * @Date 2020/4/21 23:56
 * @Created by  wrsChen
 */
@RestControllerAdvice(basePackages = "com.atguigu.product.control")
/*@ResponseBody
@ControllerAdvice*/
@Slf4j
public class GulimallExceptionCotrollerAdvice {
    /**
     * 具体异常（value = MethodArgumentNotValidException.class）
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
     log.debug("数据校验异常失败",e.getBindingResult().toString());
        Map<String, String> info = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((item) -> {
            String message = item.getDefaultMessage();
            String field = item.getField();
            info.put(field,message);
        });
        return  R.error(BizCodeEnum.UNknow_exception.getCode(), "errorSubmittingData").put("data", info);
    }

    /**
     * 精确匹配的异常如果不能处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handException(Throwable e) {
    return  R.error();
    }
}
